package com.norriekoelle.virtualsensors.client;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * Helper class for database creation and upgrade. (?)
 * 
 * @author Marion Koelle (marionkoelle)
 */
public class BookDatabaseHelper extends SQLiteOpenHelper{
	
	private static final String DATABASE_NAME = "db_books";
	private static final int DATABASE_VERSION = 1;
	private static final String DATABASE_CREATE = "create table books (_id integer primary key" +
			" autoincrement, drawable text unique not null, title text unique not null, author" +
			" text not null, url text not null, type integer not null, collection integer);";
	private static final String LOG = BookDatabaseHelper.class.getName();
	
	public BookDatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		Log.d(LOG, "Repopulating DB");
		repopulate();
	}

	@Override
	public void onCreate(SQLiteDatabase database) {
		database.execSQL(DATABASE_CREATE);
	}

	public void repopulate() {
		SQLiteDatabase database = this.getWritableDatabase();
		database.execSQL("DROP TABLE IF EXISTS books");
		database.execSQL(DATABASE_CREATE);	
	}
	
	@Override
	public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
		Log.w(LOG,
				"Upgrading database from version " + oldVersion + " to "
						+ newVersion + ", which will destroy all old data");
		database.execSQL("DROP TABLE IF EXISTS books");
		onCreate(database);
	}
}
